<template>
  <div class="appointment-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="全部" clearable style="width: 120px">
            <el-option label="待确认" value="PENDING" />
            <el-option label="已确认" value="CONFIRMED" />
            <el-option label="已完成" value="COMPLETED" />
            <el-option label="已取消" value="CANCELLED" />
          </el-select>
        </el-form-item>
        <el-form-item label="咨询师" v-if="showCounselorSearch">
          <el-input v-model="queryParams.counselorName" placeholder="请输入咨询师姓名" clearable />
        </el-form-item>
        <el-form-item label="预约时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table 
        v-loading="loading" 
        :data="appointmentList" 
        border
        style="width: 100%"
      >
        <el-table-column label="预约时间" prop="appointmentTime" min-width="180" />
        <el-table-column label="学生姓名" prop="studentName" min-width="120" />
        <el-table-column label="咨询师" prop="counselorName" min-width="120" />
        <el-table-column label="咨询类型" prop="type" min-width="120">
          <template #default="{ row }">
            {{ getTypeLabel(row.type) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" min-width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" effect="plain">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="{ row }">
            <template v-if="userRole === 'student'">
              <el-button type="primary" link @click="handleDetail(row)">查看</el-button>
            </template>
            <template v-else>
              <el-button 
                v-if="row.status === 'PENDING'"
                type="success" 
                link
                @click="handleConfirm(row)"
              >确认</el-button>
              <el-button
                v-if="['PENDING', 'CONFIRMED'].includes(row.status)"
                type="danger"
                link 
                @click="handleCancel(row)"
              >取消</el-button>
              <el-button
                v-if="row.status === 'CANCELLED' && canRevoke(row)"
                type="warning"
                link
                @click="handleRevoke(row)"
              >撤回</el-button>
              <el-button type="primary" link @click="handleDetail(row)">查看</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="appointmentList.length"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="预约详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="预约时间">
          {{ currentRow.appointmentTime || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="咨询类型">
          {{ getTypeLabel(currentRow.type) || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="学生姓名">
          {{ currentRow.studentName || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="咨询师">
          {{ currentRow.counselorName || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentRow.status)">
            {{ getStatusLabel(currentRow.status) || '-' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ currentRow.createTime || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="问题描述" :span="2">
          {{ currentRow.description || '-' }}
        </el-descriptions-item>
        <el-descriptions-item 
          v-if="currentRow.cancelReason" 
          label="取消原因" 
          :span="2"
        >
          {{ currentRow.cancelReason }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 取消预约弹窗 -->
    <el-dialog
      v-model="cancelVisible"
      title="取消预约"
      width="500px"
    >
      <el-form :model="cancelForm">
        <el-form-item label="取消原因" prop="reason">
          <el-input
            v-model="cancelForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入取消原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmCancel">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAppointmentList, confirmAppointment, cancelAppointment, revokeAppointment, getCounselorList } from '@/api/counseling'
import type { Appointment, AppointmentQuery, Counselor } from '@/types/counseling'
import { useStore } from 'vuex'

const store = useStore()
const userRole = computed(() => store.state.user.role)
const userId = computed(() => store.state.user.id)

// 获取咨询师信息
const counselorInfo = ref<Counselor | null>(null)
const counselorId = computed(() => counselorInfo.value?.id || null)

// 加载咨询师信息
const loadCounselorInfo = async () => {
  if (userRole.value !== 'counselor') return
  
  try {
    const res = await getCounselorList({
      pageNum: 1,
      pageSize: 100
    })
    if (res.code === 200) {
      // 根据当前登录用户ID找到对应的咨询师信息
      const counselor = res.data.records.find(item => item.userId === userId.value)
      console.log('找到的咨询师信息:', counselor)
      if (counselor) {
        counselorInfo.value = counselor
        // 重新获取预约列表
        getList()
      }
    }
  } catch (error) {
    console.error('加载咨询师信息失败:', error)
  }
}

// 查询参数
const queryParams = ref<AppointmentQuery>({
  pageNum: 1,
  pageSize: 10,
  status: '',
  counselorName: '',
  ...(userRole.value === 'student' 
    ? { studentId: userId.value }
    : userRole.value === 'counselor'
      ? { counselorId: counselorId.value || undefined }
      : {}),
  // 如果是咨询师，不允许查询其他咨询师的预约
  ...(userRole.value === 'counselor' ? { counselorName: '' } : {})
})

// 日期范围
const dateRange = ref<[string, string]>(['', ''])

// 数据相关
const loading = ref(false)
const total = ref(0)
const appointmentList = ref<Appointment[]>([])

// 弹窗控制
const detailVisible = ref(false)
const cancelVisible = ref(false)
const currentRow = ref<Appointment>({} as Appointment)
const cancelForm = ref({
  reason: ''
})

// 获取列表数据
const getList = async () => {
  loading.value = true
  console.log('当前用户角色:', userRole.value)
  console.log('咨询师信息:', counselorId.value)
  console.log('查询参数:', queryParams.value)
  
  // 确保咨询师只能查看自己的预约
  if (userRole.value === 'counselor' && counselorId.value) {
    queryParams.value.counselorId = counselorId.value
  }
  
  try {
    const { data } = await getAppointmentList(queryParams.value)
    console.log('API返回数据:', data)
    appointmentList.value = data.records
    total.value = data.total
  } catch (error) {
    console.error('获取预约列表失败:', error)
    ElMessage.error('获取预约列表失败，请稍后重试')
    appointmentList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 确认预约
const handleConfirm = async (row: Appointment) => {
  try {
    await ElMessageBox.confirm('确认接受此预约吗?', '提示', {
      type: 'warning'
    })
    await confirmAppointment(row.id)
    ElMessage.success('已确认预约')
    getList()
  } catch (error) {
    console.error('确认预约失败:', error)
  }
}

// 取消预约
const handleCancel = (row: Appointment) => {
  currentRow.value = row
  cancelForm.value.reason = ''
  cancelVisible.value = true
}

// 确认取消
const confirmCancel = async () => {
  if (!cancelForm.value.reason) {
    ElMessage.warning('请输入取消原因')
    return
  }
  
  try {
    await cancelAppointment(currentRow.value.id, cancelForm.value.reason)
    ElMessage.success('取消预约成功')
    cancelVisible.value = false
    getList()
  } catch (error) {
    console.error('取消预约失败:', error)
  }
}

// 查看详情
const handleDetail = (row: Appointment) => {
  currentRow.value = row
  detailVisible.value = true
}

// 工具方法
const getStatusType = (status: string | null): string => {
  if (!status) return ''
  
  const typeMap: Record<string, string> = {
    'PENDING': 'warning',
    'CONFIRMED': 'success',
    'COMPLETED': 'info',
    'CANCELLED': 'danger'
  }
  return typeMap[status] || ''
}

const getStatusLabel = (status: string | null): string => {
  if (!status) return ''
  
  const labelMap: Record<string, string> = {
    'PENDING': '待确认',
    'CONFIRMED': '已确认',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return labelMap[status] || status
}

const getTypeLabel = (type: string | null): string => {
  if (!type) return ''
  
  const typeMap: Record<string, string> = {
    'PERSONAL': '个人成长',
    'ACADEMIC': '学业问题',
    'EMOTIONAL': '情感困扰',
    'OTHER': '其他'
  }
  return typeMap[type] || type
}

// 查询和重置
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
}

const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    status: '',
    counselorName: '',
    ...(userRole.value === 'student'
      ? { studentId: userId.value }
      : userRole.value === 'counselor'
        ? { counselorId: counselorId.value || undefined }
        : {})
  }
  dateRange.value = ['', '']
  getList()
}

// 分页方法
const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val
  getList()
}

const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val
  getList()
}

// 日期范围变化
const handleDateChange = (val: [string, string]) => {
  if (val) {
    queryParams.value.startTime = val[0]
    queryParams.value.endTime = val[1]
  } else {
    queryParams.value.startTime = undefined
    queryParams.value.endTime = undefined
  }
}

// 判断是否可以撤回（24小时内且预约时间未到）
const canRevoke = (row: Appointment) => {
  const now = new Date()
  const cancelTime = new Date(row.updateTime) // 取消时间
  const appointmentTime = new Date(row.appointmentTime) // 预约时间
  
  // 24小时内可撤回
  const hoursDiff = (now.getTime() - cancelTime.getTime()) / (1000 * 60 * 60)
  
  return hoursDiff <= 24 && now < appointmentTime
}

// 撤回预约
const handleRevoke = async (row: Appointment) => {
  try {
    await ElMessageBox.confirm('确定要撤回取消操作吗？', '提示', {
      type: 'warning'
    })
    await revokeAppointment(row.id)
    ElMessage.success('撤回成功')
    getList()
  } catch (error) {
    console.error('撤回失败:', error)
  }
}

// 如果是咨询师，隐藏咨询师搜索框
const showCounselorSearch = computed(() => userRole.value !== 'counselor')

onMounted(async () => {
  console.log('当前用户信息:', {
    role: userRole.value,
    counselorId: counselorId.value,
    userId: userId.value
  })
  if (userRole.value === 'counselor') {
    // 先加载咨询师信息
    await loadCounselorInfo()
  } else {
    // 非咨询师角色（学生）直接加载列表
    await getList()
  }
})
</script>

<style lang="scss" scoped>
.appointment-container {
  padding: 20px;
  height: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  
  .search-card {
    margin-bottom: 20px;
    
    .search-form {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }
  }
  
  .table-card {
    flex: 1;
    display: flex;
    flex-direction: column;
    
    :deep(.el-card__body) {
      flex: 1;
      display: flex;
      flex-direction: column;
    }
    
    .el-table {
      flex: 1;
    }
    
    :deep(.el-tag) {
      min-width: 80px;
      justify-content: center;
    }
    
    .pagination-container {
      margin-top: 20px;
      padding: 10px 0;
      text-align: right;
    }
  }
}
</style> 